package com.itic.appbase.applications.sys.log.controller;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.common.service.InnerCommonService;
import com.itic.appbase.applications.sys.log.persistence.model.SysLog;
import com.itic.appbase.applications.sys.log.persistence.model.SysLogExample;
import com.itic.appbase.applications.sys.log.persistence.model.SysLogExample.Criteria;
import com.itic.appbase.applications.sys.log.service.SysLogService;
import com.itic.appbase.framework.common.basevo.User;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;

@Controller
@RequestMapping(value = "/sys/log")
public class SysLogController
        extends BaseController {
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private InnerCommonService innerCommonService;

    // 返回属性黑名单
    private static String[] ignoreProperties = new String[] { "createUser", "isEffective", "createTime", "updateTime",
            "orgCode" };

    /**
     * 跳转到主页面
     * 
     * @return String
     */
    @RequestMapping("/init")
    public String init() {
        return "sys/log/logMain";
    }

    /**
     * 查询日志列表
     * 
     * @param request
     * @param sysLog
     * @return Map
     * @throws IntrospectionException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> getLogList(HttpServletRequest request, SysLog sysLog) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String startTime = this.getCleanParams(request, "startTime");
        String endTime = this.getCleanParams(request, "endTime");

        // 封装查询条件
        SysLogExample example = new SysLogExample();
        example = this.handlePageQuery(request, example);
        example.setOrderByClause("log_time desc");

        Criteria criteria = example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
        if (null != sysLog) {
            if (StringHelper.isNotBlank(sysLog.getResourceName())) {
                criteria.andResourceNameLike("%" + sysLog.getResourceName() + "%");
            }

            if (StringHelper.isNotBlank(sysLog.getRealname())) {
                criteria.andRealnameLike("%" + sysLog.getRealname() + "%");
            }

            if (StringHelper.isNotBlank(sysLog.getOrgname())) {
                criteria.andOrgnameLike("%" + sysLog.getOrgname() + "%");
            }
            //时间查询
            if (StringHelper.isNotBlank(startTime)) {
                criteria.andLogTimeGreaterThanOrEqualTo(this.fixStartTime(startTime));
            }
            if (StringHelper.isNotBlank(endTime)) {
                criteria.andLogTimeLessThanOrEqualTo(this.fixEndTime(endTime));
            }
        }

        Integer total = sysLogService.count(example);
        List<SysLog> logList = sysLogService.list(example);
        List<Map<String, Object>> resultList = ValueHelper.tranList2MapList(logList, ignoreProperties);

        resultMap.put(IticConst.TOTAL_RECORDS, total); // 总数，显示总数量
        resultMap.put(IticConst.DISPLAY_RECORDS, total); // 显示display中的总数量
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode()); // 返回结果
        resultMap.put(IticConst.DATA, resultList); // 返回值
        return resultMap;
    }

    /**
     * 删除日志
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Map<String, String> delete(String ids) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        if (StringHelper.isNotBlank(ids)) {
            SysLogExample example = new SysLogExample();
            List<String> logIdList = Arrays.asList(ids.split(","));
            example.createCriteria().andIdIn(logIdList);
            SysLog sysLog = new SysLog();
            sysLog.setUpdateTime(new Date());
            sysLog.setIsEffective(DBConst.FALSE);
            result = sysLogService.deleteByExample(sysLog, example);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }

        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    public void add(HttpServletRequest request) {
        String url = request.getRequestURI().replace(request.getContextPath(), "");
        String resourceName = "";
        if (null != innerCommonService.getResourceNameByUrl(url)) {
            resourceName = innerCommonService.getResourceNameByUrl(url);
        }
        if (StringHelper.isNotBlank(resourceName)) {
            SysLog sysLog = new SysLog();
            User user = this.findUserSession(request);
            sysLog.setIp(this.toIpAddr(request));
            sysLog.setLogTime(new Date());
            sysLog.setUrl(url);
            sysLog.setResourceName(resourceName);
            sysLog.setUsername(user.getUsername());
            sysLog.setRealname(user.getRealname());
            sysLog.setOrgname(innerCommonService.getOrgByCode(user.getOrganizationCode()).getName());
            sysLog.setCreateUser(user.getId());
            sysLog.setOrgCode(user.getOrganizationCode());
            sysLogService.add(sysLog);
        }
    }

}